/**
 * 宠物小猫功能
 * - 自由走动
 * - 互动菜单
 * - 状态变化
 * - 随机对话
 */
document.addEventListener('DOMContentLoaded', () => {
    const petCat = document.getElementById('pet-cat');
    const catContainer = petCat.querySelector('.cat-container');
    const catBody = petCat.querySelector('.cat-body');
    const speechBubble = petCat.querySelector('.cat-speech-bubble');
    const speechText = speechBubble.querySelector('p');
    
    // 技术小知识库
    const techFacts = [
        "你知道吗？JavaScript的原型链是实现继承的核心机制。",
        "CSS Grid和Flexbox结合使用可以创建复杂而灵活的布局。",
        "WebAssembly让你可以在浏览器中运行接近原生速度的代码。",
        "HTTP/3使用QUIC协议，基于UDP而非TCP，提供更快的连接建立。",
        "React的虚拟DOM通过减少实际DOM操作来提高性能。",
        "TypeScript是JavaScript的超集，添加了静态类型检查。",
        "Git的分布式特性让每个开发者都拥有完整的代码历史。",
        "Docker容器共享主机OS内核，比虚拟机更轻量级。",
        "GraphQL让客户端可以精确指定需要哪些数据，减少过度获取。",
        "WebRTC允许浏览器之间进行点对点通信，无需服务器中转。"
    ];
    
    // 猫咪状态
    let catState = {
        isWalking: false,
        isJumping: false,
        isSpinning: false,
        isSleeping: false,
        isThinking: false,
        isHappy: false,
        isMenuOpen: false,
        isFollowingMouse: false,
        isRandomWalking: false,
        position: {
            x: window.innerWidth - 100,
            y: window.innerHeight - 100
        },
        target: null,
        lastRandomMove: 0,
        randomMoveInterval: 5000 // 5秒随机移动一次
    };
    
    // 互动响应
    const interactions = {
        greet: {
            responses: [
                "你好！今天过得怎么样？",
                "嗨！有什么我能帮你的吗？",
                "很高兴见到你！要一起编程吗？",
                "你好啊！今天是学习新技术的好日子！"
            ],
            action: () => {
                catBody.className = 'cat-body happy';
                catState.isHappy = true;
                
                // 跳跃动画
                catContainer.classList.add('jumping');
                setTimeout(() => {
                    catContainer.classList.remove('jumping');
                }, 500);
                
                setTimeout(() => {
                    catBody.className = 'cat-body';
                    catState.isHappy = false;
                }, 3000);
            }
        },
        play: {
            responses: [
                "耶！让我们来玩二进制猜谜游戏吧！",
                "我最喜欢追逐像素点了！",
                "要不要玩一局'捉虫'游戏？",
                "玩耍时间！我可以在屏幕上追逐你的鼠标！"
            ],
            action: () => {
                catBody.className = 'cat-body happy';
                catState.isHappy = true;
                
                // 旋转动画
                catContainer.classList.add('spinning');
                setTimeout(() => {
                    catContainer.classList.remove('spinning');
                }, 800);
                
                // 随机跳跃
                const jumpInterval = setInterval(() => {
                    if (!catState.isHappy) {
                        clearInterval(jumpInterval);
                        return;
                    }
                    
                    if (Math.random() > 0.5) {
                        catContainer.classList.add('jumping');
                        setTimeout(() => {
                            catContainer.classList.remove('jumping');
                        }, 500);
                    }
                }, 2000);
                
                // 10秒后恢复正常状态
                setTimeout(() => {
                    catBody.className = 'cat-body';
                    catState.isHappy = false;
                }, 10000);
            }
        },
        sleep: {
            responses: [
                "呼噜呼噜...做了一个关于递归的梦...",
                "ZZzzz...正在后台处理数据...",
                "正在休眠模式...节省能源中...",
                "梦见自己变成了量子计算机..."
            ],
            action: () => {
                catBody.className = 'cat-body sleeping';
                catState.isSleeping = true;
                catState.target = null; // 停止移动
                catState.isFollowingMouse = false;
                catState.isRandomWalking = false;
                
                setTimeout(() => {
                    catBody.className = 'cat-body';
                    catState.isSleeping = false;
                }, 8000);
            }
        },
        think: {
            responses: [
                "嗯...我在思考P与NP问题...",
                "如果我们把这个算法优化一下...",
                "我觉得这段代码可以重构得更优雅...",
                "思考中...量子计算会取代传统计算吗？"
            ],
            action: () => {
                catBody.className = 'cat-body thinking';
                catState.isThinking = true;
                catState.target = null; // 停止移动
                catState.isFollowingMouse = false;
                catState.isRandomWalking = false;
                
                setTimeout(() => {
                    catBody.className = 'cat-body';
                    catState.isThinking = false;
                }, 5000);
            }
        },
        follow: {
            responses: [
                "我会跟着你的鼠标走！",
                "带我去哪里？我跟着你！",
                "我是你的数字影子~",
                "跟随模式已启动！"
            ],
            action: () => {
                // 切换跟随鼠标状态
                catState.isFollowingMouse = !catState.isFollowingMouse;
                catState.isRandomWalking = false;
                
                if (catState.isFollowingMouse) {
                    document.addEventListener('mousemove', followMouseHandler);
                    showSpeech("跟随模式已启动！");
                } else {
                    document.removeEventListener('mousemove', followMouseHandler);
                    showSpeech("跟随模式已关闭！");
                }
            }
        },
        random: {
            responses: [
                "我要去探索这个界面了！",
                "随机漫步模式启动！",
                "让我看看这里有什么有趣的东西...",
                "开始巡逻任务！"
            ],
            action: () => {
                // 切换随机漫步状态
                catState.isRandomWalking = !catState.isRandomWalking;
                catState.isFollowingMouse = false;
                
                if (catState.isRandomWalking) {
                    document.removeEventListener('mousemove', followMouseHandler);
                    showSpeech("随机漫步模式已启动！");
                    // 立即触发一次随机移动
                    setRandomTarget();
                } else {
                    showSpeech("随机漫步模式已关闭！");
                    catState.target = null;
                }
            }
        }
    };
    
    // 鼠标跟随处理函数
    function followMouseHandler(e) {
        if (catState.isFollowingMouse && !catState.isSleeping && !catState.isThinking) {
            // 设置目标位置为鼠标位置，但保持一定距离
            const mouseX = e.clientX;
            const mouseY = e.clientY;
            
            // 计算猫咪和鼠标之间的距离
            const dx = mouseX - catState.position.x;
            const dy = mouseY - catState.position.y;
            const distance = Math.sqrt(dx * dx + dy * dy);
            
            // 只有当距离大于100像素时才移动
            if (distance > 100) {
                catState.target = {
                    x: mouseX,
                    y: mouseY
                };
            }
        }
    }
    
    // 设置随机目标位置
    function setRandomTarget() {
        if (!catState.isRandomWalking || catState.isSleeping || catState.isThinking) return;
        
        // 设置随机目标位置
        catState.target = {
            x: Math.random() * (window.innerWidth - 100),
            y: Math.random() * (window.innerHeight - 100)
        };
        
        // 更新最后随机移动时间
        catState.lastRandomMove = Date.now();
    }
    
    // 随机选择数组中的一项
    function getRandomItem(array) {
        return array[Math.floor(Math.random() * array.length)];
    }
    
    // 显示对话
    function showSpeech(text, duration = 3000) {
        speechText.textContent = text;
        speechBubble.style.opacity = '1';
        
        setTimeout(() => {
            speechBubble.style.opacity = '0';
        }, duration);
    }
    
    // 更新猫咪位置
    function updateCatPosition() {
        // 如果处于随机漫步模式且没有目标或已经到达目标附近
        if (catState.isRandomWalking && 
            (!catState.target || 
             Date.now() - catState.lastRandomMove > catState.randomMoveInterval)) {
            setRandomTarget();
        }
        
        // 如果有目标位置，向目标移动
        if (catState.target && !catState.isSleeping && !catState.isThinking) {
            const dx = catState.target.x - catState.position.x;
            const dy = catState.target.y - catState.position.y;
            const distance = Math.sqrt(dx * dx + dy * dy);
            
            // 如果已经接近目标，停止移动
            if (distance < 5) {
                if (!catState.isFollowingMouse && !catState.isRandomWalking) {
                    catState.target = null;
                }
                catContainer.classList.remove('walking');
                catState.isWalking = false;
                return;
            }
            
            // 计算移动方向和速度
            const speed = 2;
            const vx = (dx / distance) * speed;
            const vy = (dy / distance) * speed;
            
            // 更新位置
            catState.position.x += vx;
            catState.position.y += vy;
            
            // 设置猫咪朝向
            if (vx < 0) {
                catContainer.style.transform = 'scaleX(-1)';
            } else {
                catContainer.style.transform = 'scaleX(1)';
            }
            
            // 添加行走动画
            if (!catState.isWalking) {
                catContainer.classList.add('walking');
                catState.isWalking = true;
            }
        } else {
            // 如果没有目标，停止行走动画
            if (catState.isWalking) {
                catContainer.classList.remove('walking');
                catState.isWalking = false;
            }
        }
        
        // 应用位置
        catContainer.style.position = 'fixed';
        catContainer.style.left = `${catState.position.x}px`;
        catContainer.style.top = `${catState.position.y}px`;
        catContainer.style.bottom = 'auto';
        catContainer.style.right = 'auto';
        
        // 确保猫咪不会超出屏幕
        if (catState.position.x < 0) catState.position.x = 0;
        if (catState.position.y < 0) catState.position.y = 0;
        if (catState.position.x > window.innerWidth - 80) catState.position.x = window.innerWidth - 80;
        if (catState.position.y > window.innerHeight - 80) catState.position.y = window.innerHeight - 80;
        
        // 请求下一帧更新
        requestAnimationFrame(updateCatPosition);
    }
    
    // 初始化事件监听
    function initEvents() {
        // 点击猫咪显示/隐藏菜单
        catBody.addEventListener('click', (e) => {
            e.stopPropagation(); // 防止点击事件传播
            catContainer.classList.toggle('menu-open');
            catState.isMenuOpen = !catState.isMenuOpen;
            
            // 如果菜单关闭，显示随机对话
            if (!catState.isMenuOpen) {
                showSpeech(getRandomItem(techFacts));
            }
        });
        
        // 点击页面其他地方关闭菜单
        document.addEventListener('click', () => {
            if (catState.isMenuOpen) {
                catContainer.classList.remove('menu-open');
                catState.isMenuOpen = false;
            }
        });
        
        // 菜单项点击事件
        document.querySelectorAll('.menu-item').forEach(item => {
            item.addEventListener('click', (e) => {
                e.stopPropagation(); // 防止点击事件传播
                const action = e.currentTarget.getAttribute('data-action');
                const interaction = interactions[action];
                
                if (interaction) {
                    showSpeech(getRandomItem(interaction.responses));
                    interaction.action();
                }
                
                // 关闭菜单
                catContainer.classList.remove('menu-open');
                catState.isMenuOpen = false;
            });
        });
        
        // 双击猫咪跳跃
        catBody.addEventListener('dblclick', (e) => {
            e.stopPropagation();
            if (!catState.isJumping && !catState.isSleeping && !catState.isThinking) {
                catContainer.classList.add('jumping');
                catState.isJumping = true;
                
                setTimeout(() => {
                    catContainer.classList.remove('jumping');
                    catState.isJumping = false;
                }, 500);
                
                showSpeech("喵！我会跳跃！", 1500);
            }
        });
        
        // 拖拽猫咪
        let isDragging = false;
        let dragOffsetX = 0;
        let dragOffsetY = 0;
        
        catContainer.addEventListener('mousedown', (e) => {
            if (e.target === catBody || e.target.parentNode === catBody || e.target.parentNode.parentNode === catBody) {
                isDragging = true;
                dragOffsetX = e.clientX - catState.position.x;
                dragOffsetY = e.clientY - catState.position.y;
                
                // 停止其他移动模式
                catState.isFollowingMouse = false;
                catState.isRandomWalking = false;
                catState.target = null;
                
                document.removeEventListener('mousemove', followMouseHandler);
            }
        });
        
        document.addEventListener('mousemove', (e) => {
            if (isDragging) {
                catState.position.x = e.clientX - dragOffsetX;
                catState.position.y = e.clientY - dragOffsetY;
                
                // 确保猫咪不会超出屏幕
                if (catState.position.x < 0) catState.position.x = 0;
                if (catState.position.y < 0) catState.position.y = 0;
                if (catState.position.x > window.innerWidth - 80) catState.position.x = window.innerWidth - 80;
                if (catState.position.y > window.innerHeight - 80) catState.position.y = window.innerHeight - 80;
            }
        });
        
        document.addEventListener('mouseup', () => {
            isDragging = false;
        });
        
        // 窗口大小改变时调整猫咪位置
        window.addEventListener('resize', () => {
            // 确保猫咪不会超出屏幕
            if (catState.position.x > window.innerWidth - 80) {
                catState.position.x = window.innerWidth - 80;
            }
            if (catState.position.y > window.innerHeight - 80) {
                catState.position.y = window.innerHeight - 80;
            }
        });
        
        // 初始欢迎
        setTimeout(() => {
            showSpeech("你好！我是你的极客猫咪助手~", 5000);
        }, 2000);
        
        // 随机闲置行为
        setInterval(() => {
            // 只在不处于特殊状态时触发
            if (!catState.isHappy && !catState.isSleeping && 
                !catState.isThinking && !catState.isWalking && 
                !catState.isJumping && !catState.isSpinning && 
                !catState.isMenuOpen && !catState.isFollowingMouse && 
                !catState.isRandomWalking) {
                
                const randomAction = Math.random();
                
                if (randomAction < 0.1) {
                    // 10%几率说话
                    showSpeech(getRandomItem(techFacts));
                } else if (randomAction < 0.15) {
                    // 5%几率睡觉
                    interactions.sleep.action();
                    showSpeech(getRandomItem(interactions.sleep.responses));
                } else if (randomAction < 0.2) {
                    // 5%几率思考
                    interactions.think.action();
                    showSpeech(getRandomItem(interactions.think.responses));
                } else if (randomAction < 0.3) {
                    // 10%几率随机移动
                    catState.target = {
                        x: Math.random() * (window.innerWidth - 100),
                        y: Math.random() * (window.innerHeight - 100)
                    };
                }
            }
        }, 15000); // 每15秒检查一次
    }
    
    // 初始化
    function init() {
        // 设置初始位置
        catContainer.style.position = 'fixed';
        catContainer.style.left = `${catState.position.x}px`;
        catContainer.style.top = `${catState.position.y}px`;
        catContainer.style.bottom = 'auto';
        catContainer.style.right = 'auto';
        
        // 初始化事件
        initEvents();
        
        // 开始动画循环
        updateCatPosition();
    }
    
    // 启动
    init();
});